package threadlocal;

public class ThreadLocalDemo {

    private static final ThreadLocal<String> strThreadLocal = ThreadLocal.withInitial(() -> "初始化值");
    private static final ThreadLocal<Integer> intThreadLocal = ThreadLocal.withInitial(() -> -1);

    public static void main(String[] args) {
        // 多线程调试
        for (int i = 1; i <= 10; i++) {
            new Thread(new MyRunnable(), "线程" + i).start();
        }

        // 主线程调试
        Thread.currentThread().setName("主线程0");
        String name = Thread.currentThread().getName();
        strThreadLocal.set(name);
        intThreadLocal.set(Integer.valueOf(name.substring(name.length() - 1)));
        strThreadLocal.remove();
        //看下清除后的效果
        System.out.println(name + ":" + strThreadLocal.get() +  ":" + intThreadLocal.get());

    }

    public static class MyRunnable implements Runnable {

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            strThreadLocal.set(name);
            intThreadLocal.set(Integer.valueOf(name.substring(name.length() - 1)));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 使用
            System.out.println(name + ":" + strThreadLocal.get() + ":" + intThreadLocal.get());
            // 清除
            strThreadLocal.remove();
            intThreadLocal.remove();
            // 看下清除后的效果
            System.out.println(name + ":" + strThreadLocal.get() + ":" + intThreadLocal.get());
        }
    }
}
